<?php

/* 对模板下的文件预处理(合并) by pAUL gAO <paulgao@yeah.net> */

/* http://theme.dahai1.com/imobile.com.cn/css/a.css,imobile.com.cn/css/b.css */

class theme_index extends controller
{
    /* 强制的缓存更新周期 */
    const THEME_CACHE_EXPIRE_TIME = 300;
    const HEADER_EXPIRE_TIME      = 43200;

    public static function init()
    {
        if (!defined('IN_ESQ'))
        {
            die('Hacking attempt');
        }
    }

    public static function validate($action)
    {
        return in_array($action, array('show'));
    }

    public static function show()
    {
        if ($GLOBALS['REQUEST_INFO']['uri'] === '/')
        {
            header_status_404(', errcode: THEME1');

            exit;
        }

        /* 对 Content-Range 的考虑，要么支持，要么拒绝 */

        /* 判断 HTTP 请求的来源是否允许 */
        if (!empty($_SERVER['HTTP_REFERER']))
        {
        /* 暂无进一步内容 */
        }

        /* 生成原始文件的地址并判断是否存在 */
        $set = @parse_url('http://' . DOMAIN . '/' . $GLOBALS['REQUEST_INFO']['url']);

        if (empty($set['path']) === false)
        {
            $source_files = array_unique(explode(',', $set['path']));
        }

        if ($source_files === array())
        {
            header_status_404(', errcode: THEME2');

            exit;
        }

        /* 生成原始文件的扩展名 */
        $extname = self::get_extname_by_files($source_files);

        if ($extname === false)
        {
            header_status_404(', errcode: THEME3');

            exit;
        }

        /* 判断文件内容是否可以紧凑化 */
        switch ($extname)
        {
            case 'js':
                $compressor = 'javascript_compressor';
                break;

            case 'css':
                $compressor = 'css_compressor';
                break;

            case '.html':
            case '.htm':
                $compressor = 'html_compressor';
                break;

            default:
                $compressor = '';
                break;
        }

        /* 如果是允许压缩的请求文件，需要取出版本号，并在后面进行对比 */
        if ($compressor && isset($GLOBALS['REQUEST_INFO']['query_string']) === true)
        {
            $request_hash   = substr($GLOBALS['REQUEST_INFO']['query_string'], 0, 8);
            $file_time_hash = '';
        }
        else
        {
            $request_hash   = '';
            $file_time_hash = NULL;
        }

        $miss_file = '';
        $source_files_time = get_files_last_time($source_files, $file_time_hash, $miss_file);
        if ($source_files_time === false)
        {
            header_status_404(', errcode: THEME4, file: ' . $miss_file);

            put_file(LOG_PATH . '/404.log', date('[Y-m-d H:i:s]', REQUEST_TIME) . '->' . DOMAIN . $GLOBALS['REQUEST_INFO']['uri'] . '<-' . $_SERVER['HTTP_REFERER'] . '->' . $GLOBALS['REQUEST_INFO']['ua'] . "\r\n", FILE_APPEND);

            exit;
        }

        /* 正常流程，检查是否需要从原始文件处更新，并且允许周期性强制生成 */
        if ($compressor)
        {
            /* 生成缓存文件的地址并判断是否存在 */
            $path_md5              = md5($GLOBALS['REQUEST_INFO']['url']);
            $destination_file      = '/dev/shm/cache/theme/' . $path_md5{0} . '/' . $path_md5{1} . '/' . $path_md5;
            $destination_file_time = @filemtime($destination_file);

            if ($source_files_time >= $destination_file_time || $destination_file_time + self::THEME_CACHE_EXPIRE_TIME <= REQUEST_TIME ||
                ($request_hash !== '' && $request_hash !== $file_time_hash && $source_files_time + 60 >= REQUEST_TIME))
            {
                @unlink($destination_file);
                clearstatcache();

                $string = self::static_combine_file($source_files);
                if ($string === false)
                {
                    header_status_404(', errcode: THEME5');

                    exit;
                }

                if ($compressor)
                {
                    $string = $compressor($string);

                    if (empty($string) === true)
                    {
                        header_status_503(', errcode: THEME6');

                        exit;
                    }
                    else
                    {
                        put_file($destination_file, $string);
                    }
                }

                $content = $string;
            }
            else
            {
                $content = file_get_contents($destination_file);

                if ($content === false)
                {
                    header_status_404(', errcode: THEME7');

                    exit;
                }
            } }
        else
        {
            $content = file_get_contents(ROOT_PATH . '/' . $source_files[0]);

            if ($content === false)
            {
                header_status_404(', errcode: THEME8');

                exit;
            }
        }

        /* 支持的文件 MIME 类型 */
        $mime_types = array(
                    'js'   => 'application/x-javascript; charset=utf-8',
                    'css'  => 'text/css; charset=utf-8',
                    'gif'  => 'image/gif',
                    'jpg'  => 'image/jpeg',
                    'jpeg' => 'image/jpeg',
                    'jpe'  => 'image/jpeg',
                    'png'  => 'image/png',
                    'bmp'  => 'image/bmp',
                    'ico'  => 'image/x-icon',
                    'swf'  => 'application/x-shockwave-flash',
                    'wav'  => 'audio/x-wav',
                    'zip'  => 'application/zip',
                    'rar'  => 'application/x-rar-compressed',
                    'exe'  => 'application/octet-stream',
                    'xslt' => 'application/xslt+xml; charset=utf-8',
                    'xml'  => 'application/xml; charset=utf-8',
                    'xsl'  => 'application/xml; charset=utf-8',
        /*
        避免被利用，先暂时关闭这些文件的读取
        *//*
                    'html' => 'text/html; charset=utf-8',
                    'htm'  => 'text/html; charset=utf-8',
                    'txt'  => 'text/plain; charset=utf-8',
        */
                    );

        /* 输出 Content-Type */
        if (!empty($mime_types[$extname]))
        {
            /* 过期 HEADER 输出，并允许执行 304 判断输出 */
            if ($compressor && $request_hash !== '' && $request_hash !== $file_time_hash)
            {
                expires_header($source_files_time, 60, true);
            }
            else
            {
                expires_header($source_files_time, self::HEADER_EXPIRE_TIME, true);
            }

            esq_header('Content-Type: ' . $mime_types[$extname]);
        }
        else
        {
            /* 如果不是未定义的 MIME 类型文件，那么出错（避免比如 PHP 文件被读取） */
            header_status_404(', errcode: THEME9');

            exit;
        }

        /* 输出文件大小 */
        esq_header('Content-Length: ' . strlen($content));

        /* friendly by Squid Like */
        /* esq_header('Vary: Accept-Encoding'); */

        /* ETAG 输出 */
        output_etag($content, true);

        /* 输出文件内容 */
        echo $content;
        /* 结束啦 */
    }

    private static function get_extname_by_files($source_files)
    {
        if (is_array($source_files) === false)
        {
            $source_files = array($source);
        }

        $extname = array();
        foreach ($source_files AS $file)
        {
            $pathinfo = pathinfo($file);

            if (empty($pathinfo['extension']) === false)
            {
                $extname[] = $pathinfo['extension'];
            }
            else
            {
                return false;
            }
        }

        if ($extname === array())
        {
            return false;
        }
        elseif (count($extname) > 1)
        {
            $extname = array_unique($extname);
            if (count($extname) > 1)
            {
                return false;
            }
            else
            {
                return $extname[0];
            }
        }
        else
        {
            return $extname[0];
        }
    }

    private static function static_combine_file($source_files)
    {
        $string = '';
        foreach ($source_files AS $file)
        {
            if ($file === '' || $file === '/')
            {
                continue;
            }

            if ($file{0} === '/')
            {
                $file = substr($file, 1);
            }

            $file = realpath(ROOT_PATH . '/' . $file);

            /* 避免安全问题 */
            if (strpos($file, ROOT_PATH . '/') === false)
            {
                $string = false;

                break;
            }

            $file_string = @file_get_contents($file);
            if ($file_string === false)
            {
                $string = false;

                break;
            }
            else
            {
                /* 替换文件头部 BOM 编码 */
                if (substr($file_string, 0, 3) === "\xEF\xBB\xBF")
                {
                    $file_string = substr($file_string, 3);
                }

                $string .= $file_string;
            }
        }

        return $string;
    }
}

?>